using System;
using System.IO;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading;
using System.Text;
using System.Xml;
using Common;
using Config;
using System.Messaging;
using Apache.NMS;
using Apache.NMS.Util;
using Apache.NMS.ActiveMQ;

namespace FileTransferService
{
    public class Transfer : IDisposable
    {
        #region 基本设置
        private bool isStop = false;
        /// <summary>
        /// 线程是否停止
        /// </summary>
        public bool IsStop
        {
            set { this.isStop = value; }
            get { return this.isStop; }
        }

        private string id;
        /// <summary>
        /// 线程关联序号
        /// </summary>
        public string ID
        {
            set { this.id = value; }
            get { return this.id; }
        }
        #endregion

        #region 资源释放
        public void Dispose()
        {
            try
            {
                Dispose(true);
                GC.SuppressFinalize(this);
            }
            catch { }
        }
        protected virtual void Dispose(bool disposing)
        {

        }
        #endregion

        #region 获取：FTP下载方式
        public void DownMessages(Log log)
        {
            Ftp ftp = null;
            int iCount = 0;
            string localTmpRoot = "";
            string ftpDownRoot = "";

            string downFtpServer = "";
            int downFtpPort = 0;
            string downFtpUser = "";
            string downFtpUserPass = "";
            string downFtpRoot = "";
            string downFtpFilter = "";
            bool downFtpMode = false;
            string downFtpEncoding = "";
            bool downFtpFileRename = false;

            string fileName = "";
            string tmpFilePath = "";
            string localSavePath = "";
            int getSaveTimes = 0;
           
            try
            {
                downFtpServer = SystemSet.GetFtpServer(this.ID,false);
                downFtpPort = SystemSet.GetFtpPort(this.ID, false);
                downFtpUser = SystemSet.GetFtpUser(this.ID, false);
                downFtpUserPass = SystemSet.GetFtpUserPass(this.ID, false);
                downFtpRoot = SystemSet.GetFtpRoot(this.ID, false);
                downFtpFilter = SystemSet.GetFtpDownFileEx(this.ID);
                downFtpMode = SystemSet.GetFtpMode(this.ID, false);
                downFtpEncoding = SystemSet.GetFtpEncoding(this.ID, false);
                downFtpFileRename = SystemSet.GetFtpDownFileRename(this.ID);

                localTmpRoot = Path.Combine(AppDomain.CurrentDomain.BaseDirectory , SystemSet.TmpDownMsgPath) + "\\" + this.ID + "\\";
                if (!Directory.Exists(localTmpRoot))
                    Directory.CreateDirectory(localTmpRoot);
                localSavePath = SystemSet.GetGetMsgSavePath(this.ID);
                if (!Path.IsPathRooted(localSavePath))
                    localSavePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, localSavePath);
                if (!Directory.Exists(localSavePath))//下载本地保存目录
                    Directory.CreateDirectory(localSavePath);
                getSaveTimes = SystemSet.GetGetMsgSaveTimes(this.ID);//下载本地保存次数

                using (ftp = new Ftp(downFtpServer, downFtpRoot, downFtpUser, downFtpUserPass, Convert.ToInt32(downFtpPort)))
                {
                    ftp.PasvTransferMode = !downFtpMode;
                    if (!string.IsNullOrEmpty(downFtpEncoding))
                        ftp.FtpEncoding = downFtpEncoding;
                    if (downFtpMode)
                        ftp.LocalIp = SystemSet.ActiveFtpLocalIp;
                    ftpDownRoot = downFtpRoot;

                    string[] strFiles = null;
                    if(string.IsNullOrEmpty(downFtpFilter))
                        strFiles = ftp.Dir("*.*");
                    else
                        strFiles = ftp.Dir(downFtpFilter);
                    string[] files = OrderFile.GetOrderFiles(strFiles);
                    iCount = 0;
                    if (files != null && files.Length > 0)
                    {
                        foreach (string oFile in files)
                        {
                            if (this.IsStop || SystemSet.GetGetThreadSet(this.ID) != "1")
                                break;

                            string strFile = oFile;
                            if (!string.IsNullOrEmpty(strFile))//一般来说strFiles的最后一个元素可能是空字符串
                            {
                                fileName = Path.GetFileName(strFile);
                                try
                                {
                                    if (downFtpFileRename)
                                        ftp.Rename(fileName, fileName);
                                    ftp.Get(strFile, ftpDownRoot, localTmpRoot, "", SystemSet.IsDelete);
                                    #region 文件保存
                                    if (getSaveTimes == 1)
                                    {
                                        if (localTmpRoot != localSavePath)
                                        {
                                            if (File.Exists(Path.Combine(localSavePath, fileName)))
                                                File.Delete(Path.Combine(localSavePath, fileName));
                                            File.Move(Path.Combine(localTmpRoot, fileName), Path.Combine(localSavePath, fileName));
                                        }
                                    }
                                    else
                                    {
                                        for (int i = 0; i < getSaveTimes; i++)
                                        {
                                            tmpFilePath = Path.Combine(localSavePath, (i + 1).ToString()) + "\\" + fileName;
                                            if (!Directory.Exists(Path.GetDirectoryName(tmpFilePath)))
                                                Directory.CreateDirectory(Path.GetDirectoryName(tmpFilePath));
                                            if (File.Exists(tmpFilePath))
                                                File.Delete(tmpFilePath);
                                            if (i == getSaveTimes - 1)
                                                File.Move(Path.Combine(localTmpRoot, fileName), tmpFilePath);
                                            else
                                                File.Copy(Path.Combine(localTmpRoot, fileName), tmpFilePath, true);
                                        }
                                    }
                                    #endregion
                                }
                                catch { continue; }
                                iCount++;
                                log.WriteLogFile("[FTP下载] 下载 " + strFile + " 成功...");
                            }
                            if (SystemSet.GetAmountOneTime > 0 && iCount == SystemSet.GetAmountOneTime)
                                break;
                        }
                    }
                }
                if (iCount > 0)
                    log.WriteLogFile("[FTP下载] 本次共下载 " + iCount.ToString() + " 个！...");
            }
            catch (Exception ex)
            {
                if (log != null)
                    log.WriteLogFile("[FTP下载错误] 错误原因：" + ex.Message);
            }
        }
        #endregion

        #region 获取：本地移动方式
        public void MoveMessages(Log log)
        {
            string localRoot = "";
            string filter = "";
            string localTmpRoot = "";
            string[] strFiles = null;
            string[] orderFiles = null;
            string filePath = "";
            string tmpFilePath = "";
            string fileName = "";
            int iCount = 0;

            string getSavePath = "";
            int getSaveTimes = 0;

            try
            {
                
                localTmpRoot = Path.Combine(AppDomain.CurrentDomain.BaseDirectory , SystemSet.TmpDownMsgPath) + "\\" + this.ID + "\\";
                if (!Directory.Exists(localTmpRoot))
                    Directory.CreateDirectory(localTmpRoot);

                getSavePath = SystemSet.GetGetMsgSavePath(this.ID);//下载本地保存目录
                if (!Path.IsPathRooted(getSavePath))
                    getSavePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, getSavePath);
                if (!Directory.Exists(getSavePath))
                    Directory.CreateDirectory(getSavePath);
                getSaveTimes = SystemSet.GetGetMsgSaveTimes(this.ID);//下载本地保存次数

                localRoot = SystemSet.GetGetMsgRoot(this.ID);
                if (!Path.IsPathRooted(localRoot))
                    localRoot = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, localRoot);
                filter = SystemSet.GetGetMsgFilter(this.ID);
                if (Directory.Exists(localRoot) && localRoot != getSavePath)
                {
                    if(string.IsNullOrEmpty(filter))
                        strFiles = Directory.GetFiles(localRoot);
                    else
                        strFiles = Directory.GetFiles(localRoot, filter);
                    orderFiles = OrderFile.GetOrderFiles(strFiles);
                    for (int j = 0;!this.IsStop && SystemSet.GetGetThreadSet(this.ID) == "1" && orderFiles != null && j < orderFiles.Length; j++)
                    {
                        filePath = orderFiles[j];
                        fileName = Path.GetFileName(filePath);
                        if (File.Exists(filePath))
                        {
                            if (File.Exists(localTmpRoot + fileName))
                                File.Delete(localTmpRoot + fileName);
                            File.Move(filePath, localTmpRoot + fileName);
                            #region 文件保存
                            if (getSaveTimes == 1)
                            {
                                if (localTmpRoot != getSavePath)
                                {
                                    if (File.Exists(Path.Combine(getSavePath, fileName)))
                                        File.Delete(Path.Combine(getSavePath, fileName));
                                    File.Move(Path.Combine(localTmpRoot, fileName), Path.Combine(getSavePath, fileName));
                                }
                            }
                            else
                            {
                                for (int i = 0; i < getSaveTimes; i++)
                                {
                                    tmpFilePath = Path.Combine(getSavePath, (i + 1).ToString()) + "\\" + fileName;
                                    if (!Directory.Exists(Path.GetDirectoryName(tmpFilePath)))
                                        Directory.CreateDirectory(Path.GetDirectoryName(tmpFilePath));
                                    if (File.Exists(tmpFilePath))
                                        File.Delete(tmpFilePath);
                                    if(i == getSaveTimes - 1)
                                        File.Move(Path.Combine(localTmpRoot, fileName), tmpFilePath);
                                    else
                                        File.Copy(Path.Combine(localTmpRoot, fileName), tmpFilePath, true);
                                }
                            }
                            #endregion
                            log.WriteLogFile("[本地获取] 目录：" + localRoot + "，获取 " + Path.GetFileName(filePath) + " 成功...");
                            iCount++;
                            if (SystemSet.GetAmountOneTime > 0 && j == SystemSet.GetAmountOneTime - 1)
                                break;
                        }
                    }
                }

                if (iCount > 0)
                    log.WriteLogFile("[本地获取] 本次共获取 " + iCount.ToString() + " 个！...");
            }
            catch (Exception ex)
            {
                if (log != null)
                    log.WriteLogFile("[本地获取错误] 本地目录获取时出错！错误原因：" + ex.Message);
            }
        }
        #endregion

        #region 获取：邮件附件接收
        /// <summary>
        /// 邮件接收
        /// </summary>
        /// <param name="log"></param>
        public void EmailReceiveMessages(Log log)
        {
            string mailServer = "";
            int mailPort = 110;
            string mailUser = "";
            string mailUserPass = "";

            int mCount = 0;
            int aCount = 0;
            string tmpDown = "";
            string tmpFilePath = "";
            int getMsgSaveTimes = 0;
            string localMailTmpRoot = "";
            string localMailRoot = "";
            string getMsgSavePathTmp = "";

            ActiveUp.Net.Mail.Pop3Client pop = null;
            ActiveUp.Net.Mail.Message newMessage = null;
            string attachmentFileName = "";
            List<string> mailAttFiles = null;
            string fileName = "";

            try
            {
                #region 配置参数
                mailServer = SystemSet.GetEmailServer(this.ID, false);
                mailPort = SystemSet.GetEmailPort(this.ID, false);
                mailUser = SystemSet.GetEmailUser(this.ID, false);
                mailUserPass = SystemSet.GetEmailUserPass(this.ID, false);

                tmpDown = SystemSet.TmpDownMsgPath;
                localMailTmpRoot = Path.Combine(Path.Combine(tmpDown, this.ID), "TmpMailMessage");
                if (!Path.IsPathRooted(localMailTmpRoot))
                    localMailTmpRoot = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, localMailTmpRoot);
                if (!Directory.Exists(localMailTmpRoot))
                    Directory.CreateDirectory(localMailTmpRoot);

                localMailRoot = SystemSet.GetGetMsgSavePath(this.ID);//下载本地保存目录
                if (!Path.IsPathRooted(localMailRoot))
                    localMailRoot = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, localMailRoot);
                if (!Directory.Exists(localMailRoot))
                    Directory.CreateDirectory(localMailRoot);
                getMsgSaveTimes = SystemSet.GetGetMsgSaveTimes(this.ID);
                if (mailAttFiles == null)
                    mailAttFiles = new List<string>();
                #endregion

                try
                {
                    pop = new ActiveUp.Net.Mail.Pop3Client();
                    if (SystemSet.MailTimeOut > 0)
                    {
                        pop.ReceiveTimeout = SystemSet.MailTimeOut;
                        pop.SendTimeout = SystemSet.MailTimeOut;
                    }
                    pop.Connect(mailServer, mailPort, mailUser, mailUserPass);
                    for (int n = 1; n <= pop.MessageCount; n++)
                    {
                        newMessage = pop.RetrieveMessageObject(n);
                        mailAttFiles.Clear();

                        if (log != null)
                            log.WriteLogFile("[邮件接收] 收邮件 [" + n.ToString() + ",Subject:" + newMessage.Subject + "] 开始......");
                        for (int a = 0; a < newMessage.Attachments.Count; a++)
                        {
                            attachmentFileName = newMessage.Attachments[a].Filename;
                            if (SystemSet.MailAttFileNameAddDate)
                                attachmentFileName = Path.GetFileNameWithoutExtension(attachmentFileName) + "_"+ DateTime.Now.ToString("yyyyMMddHHmmssfff") + Path.GetExtension(attachmentFileName);
                            if (File.Exists(Path.Combine(localMailTmpRoot, attachmentFileName)))
                                File.Delete(Path.Combine(localMailTmpRoot, attachmentFileName));
                            newMessage.Attachments[a].StoreToFile(Path.Combine(localMailTmpRoot, attachmentFileName));
                            mailAttFiles.Add(attachmentFileName);
                        }

                        #region 附件处理
                        for (int t = 0; t < mailAttFiles.Count; t++)
                        {
                            fileName = mailAttFiles[t];
                            getMsgSavePathTmp = localMailRoot;
                            #region 保存
                            if (getMsgSaveTimes == 1)
                            {
                                if (localMailTmpRoot != getMsgSavePathTmp)
                                {
                                    if (File.Exists(Path.Combine(getMsgSavePathTmp, mailAttFiles[t])))
                                        File.Delete(Path.Combine(getMsgSavePathTmp, mailAttFiles[t]));
                                    File.Move(Path.Combine(localMailTmpRoot, mailAttFiles[t]), Path.Combine(getMsgSavePathTmp, mailAttFiles[t]));
                                }
                            }
                            else
                            {
                                for (int i = 0; i < getMsgSaveTimes; i++)
                                {
                                    tmpFilePath = Path.Combine(Path.Combine(getMsgSavePathTmp, (i + 1).ToString()), mailAttFiles[t]);
                                    if (!Directory.Exists(Path.GetDirectoryName(tmpFilePath)))
                                        Directory.CreateDirectory(Path.GetDirectoryName(tmpFilePath));
                                    if (File.Exists(tmpFilePath))
                                        File.Delete(tmpFilePath);
                                    if (i == getMsgSaveTimes - 1)
                                        File.Move(Path.Combine(localMailTmpRoot, mailAttFiles[t]), tmpFilePath);
                                    else
                                        File.Copy(Path.Combine(localMailTmpRoot, mailAttFiles[t]), tmpFilePath, true);
                                }
                            }
                            #endregion
                            if (log != null)
                                log.WriteLogFile("[邮件接收] 附件 " + mailAttFiles[t] + " 接收完成！");

                            aCount++;
                        }
                        #endregion

                        if (SystemSet.MailDelete)
                        {
                            pop.DeleteMessage(n);
                            if (log != null)
                                log.WriteLogFile("[邮件接收] 邮件删除 [" + n.ToString() + ",Subject:" + newMessage.Subject + "] 完成！");
                        }
                        mCount++;
                        if (log != null)
                            log.WriteLogFile("[邮件接收] 邮件 [" + n.ToString() + ",Subject:" + newMessage.Subject + "] 接收完成！");
                        if (SystemSet.GetAmountOneTime > 0 && mCount == SystemSet.GetAmountOneTime)
                            break;
                        Thread.Sleep(2);
                    }
                }
                catch (Exception exMail)
                {
                    for (int i = 0; mailAttFiles != null && i < mailAttFiles.Count; i++)
                    {
                        if (File.Exists(Path.Combine(localMailTmpRoot, mailAttFiles[i])))
                            File.Delete(Path.Combine(localMailTmpRoot, mailAttFiles[i]));
                    }
                    if (mailAttFiles != null && mailAttFiles.Count > 0)
                        mailAttFiles.Clear();

                    if (log != null)
                        log.WriteLogFile("[邮件接收错误] 错误原因：" + exMail.Message);
                }
                finally
                {
                    if (pop.IsConnected)
                    {
                        pop.Disconnect();
                        pop.CloseBaseTCPConnection();
                    }
                }

                if (mCount > 0)
                {
                    if (log != null)
                        log.WriteLogFile("[邮件接收] 本次共接收邮件 " + mCount.ToString() + " 个，附件" + aCount.ToString() + " 个！");
                }
            }
            catch (Exception ex)
            {
                if (log != null)
                    log.WriteLogFile("[邮件接收错误] 错误原因：" + ex.Message);
            }
        }
        #endregion

        #region 获取：MSMQ消息队列
        public void MsmqReceiveMessages(Log log)
        {
            string localTmpRoot = "";
            string filePath = "";
            string fileName = "";
            int iCount = 0;
            string tmpFilePath = "";
            string getSavePath = "";
            int getSaveTimes = 0;
            string getMsmqQueueName = "";
            bool getMsmqQueueTranscation = false;
            string getMsmqFileType = "";
            string getMsmqFileEncoding = "";

            System.Messaging.Message recMessage = null;
            MessageQueueTransaction mqTranscation = null;
            Encoding getEncoding = null;
            byte[] bytes = null;
            string body = "";
            bool hasMessage = true;
            XmlDocument doc = null;

            try
            {
                localTmpRoot = Path.Combine(AppDomain.CurrentDomain.BaseDirectory , SystemSet.TmpDownMsgPath) + "\\" + this.ID + "\\";
                if (!Directory.Exists(localTmpRoot))
                    Directory.CreateDirectory(localTmpRoot);

                getSavePath = SystemSet.GetGetMsgSavePath(this.ID);//下载本地保存目录
                if (!Path.IsPathRooted(getSavePath))
                    getSavePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, getSavePath);
                if (!Directory.Exists(getSavePath))
                    Directory.CreateDirectory(getSavePath);
                getSaveTimes = SystemSet.GetGetMsgSaveTimes(this.ID);//下载本地保存次数

                getMsmqQueueName = SystemSet.GetMsmqQueueName(this.ID, false);
                getMsmqQueueTranscation = SystemSet.GetMsmqTransaction(this.ID, false);
                getMsmqFileType = SystemSet.GetMsmqTxtFile(this.ID, false);
                getMsmqFileEncoding = SystemSet.GetMsmqFileEncoding(this.ID, false);
                if (string.IsNullOrEmpty(getMsmqFileEncoding))
                    getEncoding = Encoding.UTF8;
                else
                    getEncoding = Encoding.GetEncoding(getMsmqFileEncoding);

                iCount = 0;
                using(MessageQueue mq = new MessageQueue(getMsmqQueueName))
                {
                    mq.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
                    recMessage = new System.Messaging.Message();

                    while (hasMessage)
                    {
                        #region 接收消息
                        try
                        {
                            if (getMsmqQueueTranscation)
                            {
                                mqTranscation = new MessageQueueTransaction();
                                mqTranscation.Begin();
                                recMessage = mq.Receive(new TimeSpan(0, 0, 1), mqTranscation);
                            }
                            else
                                recMessage = mq.Receive(new TimeSpan(0, 0, 1));
                            fileName = recMessage.Label;
                            hasMessage = true;
                        }
                        catch (Exception exx)
                        {
                            hasMessage = false;
                            if (getMsmqQueueTranscation && mqTranscation != null)
                                mqTranscation.Abort();
                        }
                        #endregion

                        #region 转换成文件
                        if (hasMessage)
                        {
                            try
                            {
                                filePath = Path.Combine(localTmpRoot, fileName);
                                if (File.Exists(filePath))
                                    File.Delete(filePath);
                                if (getMsmqFileType == "XML")//XML文件
                                {
                                    recMessage.Formatter = new System.Messaging.XmlMessageFormatter(new System.Type[] { typeof(XmlDocument) });
                                    doc = (XmlDocument)recMessage.Body;
                                    if (doc != null)
                                    {
                                        using (XmlTextWriter xmlWrite = new XmlTextWriter(filePath, getEncoding))
                                        {
                                            //注意格式
                                            xmlWrite.Formatting = Formatting.Indented;
                                            doc.WriteTo(xmlWrite);
                                            xmlWrite.Close();
                                        }
                                    }
                                    else
                                    {
                                        body = " ";
                                        File.AppendAllText(filePath, body);
                                    }
                                }
                                else if (getMsmqFileType == "TXT")//文本文件
                                {
                                    body = (string)recMessage.Body;
                                    if (string.IsNullOrEmpty(body))
                                        body = " ";
                                    File.AppendAllText(filePath, body, getEncoding);
                                }
                                else //所有文件类型
                                {
                                    bytes = Convert.FromBase64String((string)recMessage.Body);
                                    using (FileStream outfile = new System.IO.FileStream(filePath, System.IO.FileMode.CreateNew))
                                    {
                                        outfile.Write(bytes, 0, (int)bytes.Length);
                                    }
                                }
                                #region 文件保存
                                if (getSaveTimes == 1)
                                {
                                    if (localTmpRoot != getSavePath)
                                    {
                                        if (File.Exists(Path.Combine(getSavePath, fileName)))
                                            File.Delete(Path.Combine(getSavePath, fileName));
                                        File.Move(filePath, Path.Combine(getSavePath, fileName));
                                    }
                                }
                                else
                                {
                                    for (int i = 0; i < getSaveTimes; i++)
                                    {
                                        tmpFilePath = Path.Combine(getSavePath, (i + 1).ToString()) + "\\" + fileName;
                                        if (!Directory.Exists(Path.GetDirectoryName(tmpFilePath)))
                                            Directory.CreateDirectory(Path.GetDirectoryName(tmpFilePath));
                                        if (File.Exists(tmpFilePath))
                                            File.Delete(tmpFilePath);
                                        if (i == getSaveTimes - 1)
                                            File.Move(filePath, tmpFilePath);
                                        else
                                            File.Copy(filePath, tmpFilePath, true);
                                    }
                                }
                                #endregion

                                if (getMsmqQueueTranscation)
                                    mqTranscation.Commit();
                            }
                            catch
                            {
                                if (getMsmqQueueTranscation && mqTranscation != null)
                                    mqTranscation.Abort();
                                continue;
                            }

                            log.WriteLogFile("[MSMQ接收] 获取 " + fileName + " 成功...");
                            iCount++;
                            if (SystemSet.GetAmountOneTime > 0 && iCount == SystemSet.GetAmountOneTime)
                                break;
                        }
                        #endregion
                    }
                    mq.Close();
                }

                if (iCount > 0)
                    log.WriteLogFile("[MSMQ接收] 本次共获取 " + iCount.ToString() + " 个！...");

            }
            catch (Exception ex)
            {
                if (log != null)
                    log.WriteLogFile("[MSMQ接收错误] MSMQ接收时出错！错误原因：" + ex.Message);
            }
        }
        #endregion

        #region 获取：ActiveMQ消息队列
        public void ActiveMqReceiveMessages(Log log)
        {
            string localTmpRoot = "";
            string filePath = "";
            string fileName = "";
            int iCount = 0;

            string tmpFilePath = "";
            string getSavePath = "";
            int getSaveTimes = 0;
            string getActiveMqConnectName = "";
            string getActiveMqDestinationName = "";
            bool getActiveMqTranscation = false;

            byte[] bytes = null;
            bool hasMessage = true;
            TimeSpan receiveTimeout = TimeSpan.FromSeconds(1);
            ITextMessage message = null;

            try
            {
                localTmpRoot = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,Path.Combine(SystemSet.TmpDownMsgPath ,this.ID)) + "\\";
                if (!Directory.Exists(localTmpRoot))
                    Directory.CreateDirectory(localTmpRoot);

                getSavePath = SystemSet.GetGetMsgSavePath(this.ID);//下载本地保存目录
                if (!Path.IsPathRooted(getSavePath))
                    getSavePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, getSavePath);
                if (!Directory.Exists(getSavePath))
                    Directory.CreateDirectory(getSavePath);
                getSaveTimes = SystemSet.GetGetMsgSaveTimes(this.ID);//下载本地保存次数

                getActiveMqConnectName = SystemSet.GetActiveMqConnectFactory(this.ID, false);
                getActiveMqDestinationName = SystemSet.GetActiveMqDestinationName(this.ID, false);
                getActiveMqTranscation = SystemSet.GetActiveMqTransaction(this.ID, false);

                iCount = 0;

                Uri connecturi = new Uri("activemq:" + getActiveMqConnectName);
                IConnectionFactory factory = new Apache.NMS.ActiveMQ.ConnectionFactory(connecturi);
                using (IConnection connection = factory.CreateConnection())
                using (ISession session = connection.CreateSession())
                {
                    IDestination destination = SessionUtil.GetDestination(session, getActiveMqDestinationName);
                    using (IMessageConsumer consumer = session.CreateConsumer(destination))
                    {
                        connection.Start();
                        while (hasMessage)
                        {
                            if (this.IsStop || SystemSet.GetGetThreadSet(this.ID) != "1")
                                break;
                            try
                            {
                                message = consumer.Receive(receiveTimeout) as ITextMessage;
                                if (message != null)
                                {
                                    fileName = message.NMSCorrelationID;
                                    filePath = Path.Combine(localTmpRoot, fileName);
                                    if (File.Exists(filePath))
                                        File.Delete(filePath);
                                    bytes = Convert.FromBase64String(message.Text);
                                    if (bytes == null || bytes.Length == 0)
                                        bytes = new byte[] { Convert.ToByte("0") };
                                    using (FileStream outfile = new System.IO.FileStream(filePath, System.IO.FileMode.CreateNew))
                                    {
                                        outfile.Write(bytes, 0, (int)bytes.Length);
                                    }
                                    #region 文件保存
                                    if (getSaveTimes == 1)
                                    {
                                        if (filePath != Path.Combine(getSavePath, fileName))
                                        {
                                            if (File.Exists(Path.Combine(getSavePath, fileName)))
                                                File.Delete(Path.Combine(getSavePath, fileName));
                                            File.Move(filePath, Path.Combine(getSavePath, fileName));
                                        }
                                    }
                                    else
                                    {
                                        for (int i = 0; i < getSaveTimes; i++)
                                        {
                                            tmpFilePath = Path.Combine(getSavePath, (i + 1).ToString()) + "\\" + fileName;
                                            if (!Directory.Exists(Path.GetDirectoryName(tmpFilePath)))
                                                Directory.CreateDirectory(Path.GetDirectoryName(tmpFilePath));
                                            if (File.Exists(tmpFilePath))
                                                File.Delete(tmpFilePath);
                                            if (i == getSaveTimes - 1)
                                                File.Move(filePath, tmpFilePath);
                                            else
                                                File.Copy(filePath, tmpFilePath, true);
                                        }
                                    }
                                    #endregion
                                    if (session.Transacted)
                                        session.Commit();

                                    log.WriteLogFile("[ActiveMQ接收] 获取 " + fileName + " 成功...");
                                    iCount++;
                                    if (SystemSet.GetAmountOneTime > 0 && iCount == SystemSet.GetAmountOneTime)
                                        break;
                                }
                                else
                                    hasMessage = false;
                            }
                            catch (Exception debug)
                            {
                                continue;
                            }
                        }
                    }
                }

                if (iCount > 0)
                    log.WriteLogFile("[ActiveMQ接收] 本次共获取 " + iCount.ToString() + " 个！...");
            }
            catch (Exception ex)
            {
                if (ex.Message.IndexOf("正在中止线程") == -1)
                {
                    if (log != null)
                        log.WriteLogFile("[ActiveMQ接收错误] ActiveMQ接收时出错！错误原因：" + ex.Message);
                }
            }
        }
        #endregion

        #region 获取
        /// <summary>
        /// 获取
        /// </summary>
        public void GetMessages()
        {
            Log log = null;
            string strCorpNo = "";
            int sleepTime = 0;
            string logPath = "";
            string getMode = "";
            try
            {
                while (!this.IsStop)
                {
                    try
                    {
                        sleepTime = SystemSet.GetGetThreadTime(this.ID);
                        if (this.ID != "" && this.ID != null)
                            strCorpNo = this.ID + "\\";

                        logPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, SystemSet.LogPath) + "\\Get\\" + strCorpNo + DateTime.Now.Year.ToString() + "\\" + DateTime.Now.ToString("yyyy-MM") + "\\" + "log_" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";
                        if (log == null)
                            log = new Log(logPath, 0);

                        if(log.FilePath != logPath)
                            log.FilePath = logPath;

                        if (this.ID == null)
                        {
                            Thread.Sleep(sleepTime * 1000);
                            continue;
                        }

                        if (SystemSet.GetGetThreadSet(this.ID) != "1")
                        {
                            Thread.Sleep(sleepTime * 1000);
                            continue;
                        }

                        if (!Directory.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory+"\\"+SystemSet.TmpDownMsgPath, this.ID)))
                            Directory.CreateDirectory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "\\" + SystemSet.TmpDownMsgPath, this.ID));

                        getMode = SystemSet.GetGetMsgMode(this.ID);
                        if (getMode == "0")
                            this.MoveMessages(log);
                        else if (getMode == "1")
                            this.DownMessages(log);
                        else if (getMode == "2")
                            this.EmailReceiveMessages(log);
                        else if (getMode == "3")
                            this.MsmqReceiveMessages(log);
                        else if (getMode == "4")
                            this.ActiveMqReceiveMessages(log);
                    }
                    catch (Exception ex)
                    {
                        if (ex.Message.IndexOf("正在中止线程") == -1)
                            log.WriteLogFile("[获取错误] 获取出错！错误原因：" + ex.Message);
                    }
                    if (this.IsStop)
                        break;
                    Thread.Sleep(sleepTime * 1000);
                }
            }
            catch { }
        }
        #endregion

        #region 上传
        /// <summary>
        /// 上传
        /// </summary>
        public void UpMessages()
        {
            Log log = null;
            string strCorpNo = "";
            string uploadMode = "";
            int sleepTime = 0;
            string logPath = "";

            try
            {
                while (!this.IsStop)
                {
                    try
                    {
                        sleepTime = SystemSet.GetUploadThreadSetTime(this.ID);
                        if (this.ID != "" && this.ID != null)
                            strCorpNo = this.ID + "\\";
                        logPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, SystemSet.LogPath) + "\\Send\\" + strCorpNo + DateTime.Now.Year.ToString() + "\\" + DateTime.Now.ToString("yyyy-MM") + "\\" + "log_" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";
                        if (log == null)
                            log = new Log(logPath, 0);
                        if( log.FilePath != logPath)
                            log.FilePath = logPath;
                        //线程开关
                        if (SystemSet.GetUploadThreadSet(this.ID) != "1")
                        {
                            Thread.Sleep(sleepTime * 1000);
                            continue;
                        }

                        uploadMode = SystemSet.GetUoloadMsgMode(this.ID);
                        if (uploadMode == "0")
                            this.UploadMessages(log);
                        else if (uploadMode == "1")
                            this.EmailSendMessages(log);
                        else if (uploadMode == "2")
                            this.MsmqSendMessages(log);
                        else if (uploadMode == "3")
                            this.ActiveMqSendMessages(log);
                    
                    }
                    catch (Exception ex)
                    {
                        if (ex.Message.IndexOf("正在中止线程") == -1)
                        {
                            if (log != null)
                                log.WriteLogFile("[上传错误] 上传时出错！错误原因：" + ex.Message);
                        }
                    }
                    Thread.Sleep(sleepTime * 1000);
                }
            }
            catch { }
        }
        #endregion

        #region 上传：FTP上传方式
        /// <summary>
        /// FTP上传
        /// </summary>
        /// <param name="log"></param>
        private void UploadMessages(Log log)
        {
            Ftp ftp = null;
            string[] files = null;
            int iCount = 0;
            string localRoot = "";
            string filter = "";
            string[] orderFiles = null;
            string fileName = "";
            string filePath = "";
            string uploadTmpRoot = "";

            string ftpServer = "";
            int ftpPort = 0;
            string ftpUser = "";
            string ftpUserPass = "";
            string ftpRemoteRoot = "";
            string ftpEncoding = "";
            bool ftpMode = false;

            try
            {
                ftpServer = SystemSet.GetFtpServer(this.ID, true);
                ftpPort = SystemSet.GetFtpPort(this.ID, true);
                ftpUser = SystemSet.GetFtpUser(this.ID, true);
                ftpUserPass = SystemSet.GetFtpUserPass(this.ID, true);
                ftpRemoteRoot = SystemSet.GetFtpRoot(this.ID, true);
                ftpEncoding = SystemSet.GetFtpEncoding(this.ID, true);
                ftpMode = SystemSet.GetFtpMode(this.ID, true);

                localRoot = SystemSet.GetUploadLoaclRoot(this.ID);
                filter = SystemSet.GetUploadLoaclRootFilter(this.ID);
                uploadTmpRoot = Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,SystemSet.TmpUpMsgPath), this.ID) + "\\";

                #region 上传
                if (Directory.Exists(localRoot))
                {
                    if (!string.IsNullOrEmpty(filter))
                        files = Directory.GetFiles(localRoot, filter);
                    else
                        files = Directory.GetFiles(localRoot);
                    orderFiles = OrderFile.GetOrderFiles(files);
                }
                if (orderFiles != null && orderFiles.Length > 0)
                {
                    using (ftp = new Ftp(ftpServer, ftpRemoteRoot, ftpUser, ftpUserPass, ftpPort))
                    {
                        if (!string.IsNullOrEmpty(ftpEncoding))
                            ftp.FtpEncoding = ftpEncoding;
                        ftp.PasvTransferMode = !ftpMode;
                        if (ftpMode)
                            ftp.LocalIp = SystemSet.ActiveFtpLocalIp;

                        #region 上传文件
                        foreach (string strFile in orderFiles)
                        {
                            if ( this.IsStop || SystemSet.GetUploadThreadSet(this.ID) != "1")
                                break;
                            try
                            {
                                if (File.Exists(strFile) && string.IsNullOrEmpty(File.ReadAllText(strFile)))
                                    continue;
                            }catch
                            {
                                continue;
                            }

                            try
                            {
                                fileName = Path.GetFileName(strFile);
                                filePath = strFile;

                                if (!Directory.Exists(uploadTmpRoot))
                                    Directory.CreateDirectory(uploadTmpRoot);
                                if (File.Exists(Path.Combine(uploadTmpRoot,fileName)))
                                    File.Delete(Path.Combine(uploadTmpRoot, fileName));
                                File.Move(filePath, Path.Combine(uploadTmpRoot, fileName));
                                filePath = Path.Combine(uploadTmpRoot, fileName);
                                ftp.Put(filePath, "");
                                //备份文件
                                if (SystemSet.IsUpBackup)
                                    this.MoveUploadOkFile(this.ID, filePath, fileName, log);
                                else
                                    File.Delete(filePath);

                                log.WriteLogFile("[FTP上传] 本地目录：" + localRoot + ",上传目录：" + ftpRemoteRoot + "，上传 " + fileName + " 成功.");
                                iCount++;
                                if (SystemSet.UploadAmountOneTime > 0 && iCount == SystemSet.UploadAmountOneTime)
                                    break;
                            }
                            catch 
                            {
                                if (File.Exists(filePath))
                                    File.Move(filePath, Path.Combine(localRoot, fileName));

                                continue; 
                            }
                        }
                        #endregion
                    }
                }
                #endregion

                if (iCount > 0)
                    log.WriteLogFile("[FTP上传] 本次共上传 " + iCount.ToString() + " 个！");
            }
            catch (Exception ex)
            {
                  if (log != null)
                      log.WriteLogFile("[FTP上传错误] 错误原因：" + ex.Message);
            }
        }
        #endregion

        #region 上传：邮件附件方式
        /// <summary>
        /// 邮件附件发送
        /// </summary>
        /// <param name="log"></param>
        private void EmailSendMessages(Log log)
        {
            Email mail = null;
            string[] files = null;
            string[] orderFiles = null;
            int iCount = 0;
            string localRoot = "";
            string filter = "";
            string fileName = "";
            string filePath = "";
            string uploadTmpRoot = "";
            string server = "";
            int port = 0;
            string user = "";
            string userPass = "";
            string to = "";

            try
            {
                server = SystemSet.GetEmailServer(this.ID, true);
                port = SystemSet.GetEmailPort(this.ID, true);
                user = SystemSet.GetEmailUser(this.ID, true);
                userPass = SystemSet.GetEmailUserPass(this.ID, true);
                to = SystemSet.GetEmailTo(this.ID, true);

                localRoot = SystemSet.GetUploadLoaclRoot(this.ID);
                filter = SystemSet.GetUploadLoaclRootFilter(this.ID);

                #region 上传
                if (Directory.Exists(localRoot))
                {
                    if (filter != "")
                        files = Directory.GetFiles(localRoot, filter);
                    else
                        files = Directory.GetFiles(localRoot);
                    orderFiles = OrderFile.GetOrderFiles(files);
                }
                if (orderFiles != null && orderFiles.Length > 0)
                {
                    mail = new Email();
                    mail.Server = server;
                    mail.SendUser = user;
                    mail.Port = port;
                    mail.Password = userPass;
                    mail.SendUserName = user;
                    mail.ToAddrs = to.Split(new char[]{';','；'});

                    #region 上传文件
                    foreach (string strFile in orderFiles)
                    {
                        if (this.IsStop || SystemSet.GetUploadThreadSet(this.ID) != "1")
                            break;
                        try
                        {
                            fileName = Path.GetFileName(strFile);
                            filePath = strFile;

                            uploadTmpRoot = Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, SystemSet.TmpUpMsgPath), this.ID)+"\\";
                            if (!Directory.Exists(uploadTmpRoot))
                                Directory.CreateDirectory(uploadTmpRoot);
                            if (File.Exists(Path.Combine(uploadTmpRoot, fileName)))
                                File.Delete(Path.Combine(uploadTmpRoot, fileName));
                            File.Move(filePath, Path.Combine(uploadTmpRoot, fileName));
                            filePath = Path.Combine(uploadTmpRoot, fileName);
                           
                            mail.Subject = "FT File";
                            mail.Body = "FT Message,one attachment included.";
                            mail.Attachments = new string[] { filePath };
                            mail.SendMail();

                            //备份文件
                            if (SystemSet.IsUpBackup)
                                this.MoveUploadOkFile(this.ID, filePath, fileName, log);
                            else
                                File.Delete(filePath);

                            log.WriteLogFile("[邮件发送] 本地目录：" + localRoot + "，邮件服务器：" + server + ":" + port.ToString()+"，发送 " + fileName + " 成功.");
                            iCount++;
                            if (SystemSet.UploadAmountOneTime > 0 && iCount == SystemSet.UploadAmountOneTime)
                                break;
                        }
                        catch(Exception errEx)
                        {
                            if (File.Exists(filePath))
                                File.Move(filePath, Path.Combine(localRoot, fileName));

                            log.WriteLogFile("[邮件发送] 邮件发送出错！错误原因：" + errEx.Message);
                            continue;
                        }
                    }
                    #endregion
                }
                #endregion

                if (iCount > 0)
                    log.WriteLogFile("[邮件发送] 本次共发送 " + iCount.ToString() + " 个！");
            }
            catch (Exception ex)
            {
                if (log != null)
                    log.WriteLogFile("[邮件发送错误] 错误原因：" + ex.Message);
            }

        }
        #endregion

        #region 上传：MSMQ消息队列
        public void MsmqSendMessages(Log log)
        {
            string[] files = null;
            int iCount = 0;

            string[] orderFiles = null;
            string fileName = "";
            string filePath = "";

            string uploadTmpRoot = "";
            string localRoot = "";
            string fileFilter = "";

            string sendMsmqQueueName = "";
            bool sendMsmqQueueTranscation = false;
            string sendMsmqFileType = "";
            string sendMsmqFileEncoding = "";
            Encoding sendEncoding = null;

            XmlDocument doc = null;
            System.Messaging.Message recMessage = null;
            MessageQueueTransaction mqTranscation = null;
            byte[] bytes = null;

            try
            {
                localRoot = SystemSet.GetUploadLoaclRoot(this.ID);
                fileFilter = SystemSet.GetUploadLoaclRootFilter(this.ID);
                uploadTmpRoot = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + SystemSet.TmpUpMsgPath, this.ID) + "\\";
                if (!Directory.Exists(uploadTmpRoot))
                    Directory.CreateDirectory(uploadTmpRoot);

                if (Directory.Exists(localRoot))
                {
                    if (fileFilter != "")
                        files = Directory.GetFiles(localRoot, fileFilter);
                    else
                        files = Directory.GetFiles(localRoot);
                    orderFiles = OrderFile.GetOrderFiles(files);
                }
                if (orderFiles != null && orderFiles.Length > 0)
                {
                    #region 上传文件
                    sendMsmqQueueName = SystemSet.GetMsmqQueueName(this.ID, true);
                    sendMsmqQueueTranscation = SystemSet.GetMsmqTransaction(this.ID, true);
                    sendMsmqFileType = SystemSet.GetMsmqTxtFile(this.ID, true);
                    sendMsmqFileEncoding = SystemSet.GetMsmqFileEncoding(this.ID, true);
                    if (string.IsNullOrEmpty(sendMsmqFileEncoding))
                        sendEncoding = Encoding.UTF8;
                    else
                        sendEncoding = Encoding.GetEncoding(sendMsmqFileEncoding);

                    MessageQueue mq = new MessageQueue(sendMsmqQueueName);
                    if (sendMsmqQueueTranscation)
                        mqTranscation = new MessageQueueTransaction();
                    foreach (string strFile in orderFiles)
                    {
                        if (this.IsStop || SystemSet.GetUploadThreadSet(this.ID) != "1")
                            break;
                        try
                        {
                            fileName = Path.GetFileName(strFile);
                            filePath = strFile;
                            if (File.Exists(uploadTmpRoot + fileName))
                                File.Delete(uploadTmpRoot + fileName);
                            File.Move(filePath, uploadTmpRoot + fileName);
                            filePath = uploadTmpRoot + fileName;
                            #region MSMQ发送消息
                            try
                            {
                                recMessage = new System.Messaging.Message();
                                if (sendMsmqFileType == "XML")
                                {
                                    using (StreamReader reader = new StreamReader(filePath, sendEncoding))
                                    {
                                        doc = new XmlDocument();
                                        doc.Load(reader);
                                        reader.Close();
                                    }
                                    recMessage.Formatter = new System.Messaging.XmlMessageFormatter(new System.Type[] { typeof(XmlDocument) });
                                    recMessage.Body = doc;
                                }
                                else if (sendMsmqFileType == "TXT")
                                {
                                    recMessage.Body = File.ReadAllText(filePath, sendEncoding);
                                }
                                else
                                {
                                    using (FileStream inFile = new FileStream(filePath, FileMode.Open, System.IO.FileAccess.Read))
                                    {
                                        bytes = new byte[inFile.Length];
                                        inFile.Read(bytes, 0, (int)inFile.Length);
                                    }
                                    recMessage.Body = Convert.ToBase64String(bytes);
                                }

                                if (sendMsmqQueueTranscation)
                                {
                                    mqTranscation.Begin();
                                    mq.Send(recMessage, fileName, mqTranscation);
                                    mqTranscation.Commit();
                                }
                                else
                                    mq.Send(recMessage, fileName);
                            }
                            catch (Exception eex)
                            {
                                if (sendMsmqQueueTranscation && mqTranscation != null)
                                    mqTranscation.Abort();

                                throw eex;
                            }
                            #endregion
                            //备份文件
                            if (SystemSet.IsUpBackup)
                                this.MoveUploadOkFile(this.ID, filePath, fileName, log);
                            else
                                File.Delete(filePath);
                            log.WriteLogFile("[MSMQ发送] 本地目录：" + localRoot + "，上传 " + fileName + " 成功.");
                            iCount++;
                            if (SystemSet.UploadAmountOneTime > 0 && iCount == SystemSet.UploadAmountOneTime)
                                break;
                        }
                        catch
                        {
                            if (File.Exists(filePath))
                                File.Move(filePath, Path.Combine(localRoot, fileName));

                            continue;
                        }
                    }
                    mq.Close();
                    #endregion
                }

                if (iCount > 0)
                    log.WriteLogFile("[MSMQ发送] 本次共发送 " + iCount.ToString() + " 个！");
            }
            catch (Exception ex)
            {
                if (log != null)
                    log.WriteLogFile("[MSMQ发送错误] 错误原因：" + ex.Message);
            }
        }
        #endregion

        #region 上传：ActiveMQ消息队列
        public void ActiveMqSendMessages(Log log)
        {
            string[] files = null;
            int iCount = 0;
            string[] orderFiles = null;
            string fileName = "";
            string filePath = "";

            string uploadTmpRoot = "";
            string localRoot = "";
            string fileFilter = "";

            string sendActiveMqConnectName = "";
            string sendActiveMqDestinationName = "";
            bool sendActiveMqTranscation = false;

            ITextMessage request = null;
            byte[] bytes = null;
            FileStream inFile = null;

            try
            {
                localRoot = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,SystemSet.GetUploadLoaclRoot(this.ID));
                uploadTmpRoot = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + SystemSet.TmpUpMsgPath, this.ID) + "\\";
                if (!Directory.Exists(uploadTmpRoot))
                    Directory.CreateDirectory(uploadTmpRoot);

                if (Directory.Exists(localRoot))
                {
                    fileFilter = SystemSet.GetUploadLoaclRootFilter(this.ID);
                    if (fileFilter != "")
                        files = Directory.GetFiles(localRoot, fileFilter);
                    else
                        files = Directory.GetFiles(localRoot);
                    orderFiles = OrderFile.GetOrderFiles(files);
                }
                if (orderFiles != null && orderFiles.Length > 0)
                {
                    sendActiveMqConnectName = SystemSet.GetActiveMqConnectFactory(this.ID, true);
                    sendActiveMqDestinationName = SystemSet.GetActiveMqDestinationName(this.ID, true);
                    sendActiveMqTranscation = SystemSet.GetActiveMqTransaction(this.ID, true);

                    Uri connecturi = new Uri("activemq:" + sendActiveMqConnectName);
                    IConnectionFactory factory = new Apache.NMS.ActiveMQ.ConnectionFactory(connecturi);
                    using (IConnection connection = factory.CreateConnection())
                    using (ISession session = connection.CreateSession())
                    {
                        IDestination destination = SessionUtil.GetDestination(session, sendActiveMqDestinationName);
                        using (IMessageProducer producer = session.CreateProducer(destination))
                        {
                            connection.Start();
                            producer.DeliveryMode = MsgDeliveryMode.Persistent;

                            #region 传送文件
                            foreach (string strFile in orderFiles)
                            {
                                if (this.IsStop || SystemSet.GetUploadThreadSet(this.ID) != "1")
                                    break;
                                try
                                {
                                    fileName = Path.GetFileName(strFile);
                                    filePath = strFile;

                                    if (File.Exists(uploadTmpRoot + fileName))
                                        File.Delete(uploadTmpRoot + fileName);
                                    File.Move(filePath, uploadTmpRoot + fileName);
                                    filePath = uploadTmpRoot + fileName;
                                    #region ActiveMQ发送消息
                                    using (inFile = new FileStream(filePath, FileMode.Open, System.IO.FileAccess.Read))
                                    {
                                        bytes = new byte[inFile.Length];
                                        inFile.Read(bytes, 0, (int)inFile.Length);
                                    }

                                    request = session.CreateTextMessage();
                                    request.NMSCorrelationID = fileName;
                                    if (bytes != null && bytes.Length > 0)
                                        request.Text = Convert.ToBase64String(bytes);

                                    producer.Send(request);

                                    if (session.Transacted)
                                        session.Commit();
                                    #endregion

                                    //备份文件
                                    if (SystemSet.IsUpBackup)
                                        this.MoveUploadOkFile(this.ID, filePath, fileName, log);
                                    else
                                        File.Delete(filePath);

                                    log.WriteLogFile("[ActiveMQ发送] 本地目录：" + localRoot + "，上传 " + fileName + " 成功.");
                                    iCount++;
                                    if (SystemSet.UploadAmountOneTime > 0 && iCount == SystemSet.UploadAmountOneTime)
                                        break;
                                }
                                catch (Exception debug)
                                {
                                    if (File.Exists(filePath))
                                        File.Move(filePath, Path.Combine(localRoot, fileName));

                                    continue;
                                }
                            }
                            #endregion
                        }
                    }
                }

                if (iCount > 0)
                    log.WriteLogFile("[ActiveMQ发送] 本次共发送 " + iCount.ToString() + " 个！");
            }
            catch (Exception ex)
            {
                if (log != null)
                    log.WriteLogFile("[ActiveMQ发送错误] 错误原因：" + ex.Message);
            }
        }
        #endregion

        #region 公共方法
        /// <summary>
        /// 备份上传
        /// </summary>
        /// <param name="corpNo"></param>
        /// <param name="filePath"></param>
        /// <param name="fileName"></param>
        /// <param name="log"></param>
        private void MoveUploadOkFile(string taskNo, string filePath, string fileName, Log log)
        {
            try
            {
                string tFile = "";
                if (!string.IsNullOrEmpty(taskNo))
                    tFile = AppDomain.CurrentDomain.BaseDirectory + SystemSet.LocalSuccessPath + "UpLoad\\" + taskNo + "\\" + System.DateTime.Now.Year.ToString() + "\\" + System.DateTime.Now.ToString("yyyy-MM") + "\\" + System.DateTime.Now.ToString("yyyy-MM-dd") + "\\" + fileName;
                else
                    tFile = AppDomain.CurrentDomain.BaseDirectory + SystemSet.LocalSuccessPath + "UpLoad\\" + System.DateTime.Now.Year.ToString() + "\\" + System.DateTime.Now.ToString("yyyy-MM") + "\\" + System.DateTime.Now.ToString("yyyy-MM-dd") + "\\" + fileName;

                if (!Directory.Exists(Path.GetDirectoryName(tFile)))
                    Directory.CreateDirectory(Path.GetDirectoryName(tFile));
                if (File.Exists(tFile))
                    File.Delete(tFile);
                File.Move(filePath, tFile);
            }
            catch (Exception ex)
            {
                log.WriteLogFile("[移动错误] 上传成功！移动" + fileName + "时出错！错误原因：" + ex.Message);
            }
        }
        #endregion
    }
}
